// 文章列表组件

import styles from './index.module.scss'
import ArticleItem from '../ArticleItem'
import { useEffect, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { getArticleList, getMoreArticleList } from '@/store/actions/home'
import { PullToRefresh, InfiniteScroll } from 'antd-mobile-v5'

/**
 * 文章列表组件
 * @param {String} props.channelId 当前文章列表所对应的频道ID
 * @param {String} props.aid 当前 Tab 栏选中的频道ID
 */
const ArticleList = ({ channelId, activeId }) => {
  const dispatch = useDispatch()
  // 获取文章列表数据
  const current = useSelector((state) => state.home.articles[channelId])

  // 是否有更多数据
  const [hasMore, setHasMore] = useState(true)

  // 是否正在加载数据
  const [loading, setLoading] = useState(false)

  // 上拉加载更多
  const loadMore = async () => {
    // 加载中不需要重复加载
    if (loading) return
    // 不是当前频道不需要加载
    if (channelId !== activeId) return
    // 返回current没有timestamp说明没有更多数据了就不需要继续加载了
    if (!current.timestamp) {
      setHasMore(false)
      return
    }
    setLoading(true)
    try {
      await dispatch(getMoreArticleList(channelId, current.timestamp))
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    // 该频道有文章数据就不用一进来发送请求
    if (current) return
    // 只加载选中项的数据
    if (channelId === activeId) {
      dispatch(getArticleList(channelId, Date.now()))
    }
  }, [channelId, activeId, dispatch, current])

  // 只拿当前选中频道的文章，其它频道的文章列表数据为undefined
  if (!current) return null
  const list = current.list

  // 列表下拉刷新
  const onRefresh = async () => {
    await dispatch(getArticleList(channelId, Date.now()))
  }

  return (
    <div className={styles.root}>
      <PullToRefresh onRefresh={onRefresh}>
        <div className="articles">
          {list.map((item) => (
            <div className="article-item" key={item.art_id}>
              <ArticleItem article={item}></ArticleItem>
            </div>
          ))}
        </div>
      </PullToRefresh>
      {/* 上拉加载更多 */}
      <InfiniteScroll hasMore={hasMore} loadMore={loadMore}></InfiniteScroll>
    </div>
  )
}

export default ArticleList
